package com.itheima.test7;

import java.io.*;

public class Test {
    //复制一个文件夹到另一个文件夹中，复制内容包括文件夹中的内容
    public static void main(String[] args) throws IOException {
        String path = "D:\\新建文件夹";
        String copyPath = "D:\\test\\1234";
        copyDir(path, copyPath);
        System.out.println("------------");
    }

    public static void copyDir(String path, String copyPath) throws IOException {
        File file = new File(path);
        File copyFile = new File(copyPath);
        if (!file.exists()) {
            return;
        }
        if (!copyFile.exists()) {
            copyFile.mkdirs();
        }
        File[] files = file.listFiles();
        for (File f : files) {

            String child = f.getName();
            File childCopyFile = new File(copyPath, child);
            String newCopyPath = childCopyFile.getAbsolutePath();

            if (f.isFile()) {
                childCopyFile.createNewFile();
                copyFile(f, newCopyPath);
            } else {
                childCopyFile.mkdirs();

                String newPath = f.getAbsolutePath();
                copyDir(newPath, newCopyPath);
            }
        }
    }

    private static void copyFile(File f, String copyPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(f);
            fos = new FileOutputStream(copyPath);

            int b;
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }

            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
